import { globalErrorType } from '../errorMsg'
import { Controller } from 'egg';
// 写一个通用验证的装饰器
// 创建工厂函数传入 rules和errorType
export default function validateInput(rules: any, errorType: globalErrorType) {
  return function(prototype, key: string, descriptor: PropertyDescriptor) {
    const originalMethod = descriptor.value;
    descriptor.value = async function(...args: any[]) {
      const that = this as Controller;
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-ignore
      const { ctx, app } = that;
      const error = app.validator.validate(rules, ctx.request.body);
      if (error) {
        return ctx.helper.error({ ctx, errorType, error })
      }
      await originalMethod.apply(this, args)
    }
  }
}
